import React, {useEffect, useRef, useState} from "react";
import {ActionType, PageContainer, ProTable} from "@ant-design/pro-components";
import {getAllRedPackets} from "@/services/redpacket/redpacket";
import moment from "moment";
import {getDepartmentMembers, getDepartments} from "@/services/department/department";
import {TreeDataNode, TreeSelect, Spin, message} from "antd";
import {getGroups} from "@/services/group/group";

const RedPacket = () => {
  const [loading, setLoading] = useState(false);

  const actionRef = useRef<ActionType>();

  const [currentIndex, setCurrentIndex] = useState(0)
  const [size, setSize] = useState(10)
  const [departments, setDepartments] = useState([])
  const [sales, setSales] = useState([])
  const [wechatGroups, setWechatGroups] = useState([])

  const getDepartmentList = async () => {
    const msg = await getDepartments()
    console.log('all departments', msg.data)
    const buildTreeNodes = async (departments) => {
      const findChildren = (parent) => {
        return departments.filter(department => department.parentId === parent.wxDid)
          .map(department => {
            const item: TreeDataNode = {
              key: department.wxDid,
              value: department.wxDid,
              title: department.name,
              parentId: department.parentId,
              children: findChildren(department)
            }
            return item
          })
      };
      const rootNodes = departments.filter(department => department.parentId === 0)
        .map(department => {
          const item: TreeDataNode = {
            key: department.wxDid,
            value: department.wxDid,
            title: department.name,
            parentId: department.parentId,
            children: findChildren(department)
          }
          return item
        });
      return rootNodes;
    }
    const departmentSelectData = await buildTreeNodes(msg.data);
    setDepartments(departmentSelectData)
  }
  const getSalesList = async () => {
    const res = await getDepartmentMembers({
      page: 1,
      size: 9999,
    })
    console.log('all sales', res)
    const sales = []
    res.data.records.forEach(sale => {
      sales.push({
        title: sale.name,
        value: sale.wxUid
      })
    })
    setSales(sales)
  }
  const getWechatGroups = async () => {
    const res = await getGroups({page: 1, size: 9999})
    if (res.code !== 1) {
      message.error('获取微信群列表失败,' + res.msg)
      return
    }
    console.log('all wechat groups', res)
    const wechatGroups = []
    res.data.records.forEach(group => {
      wechatGroups.push({
        title: group.groupName,
        label: group.groupName,
        value: group.wxGid,
      })
    })
    setWechatGroups(wechatGroups)
  }
  useEffect(() => {
    getDepartmentList()
    getSalesList()
    getWechatGroups()
  }, []);

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch: true,
    }, {
      title: '微信昵称',
      dataIndex: 'nickname',
      hideInSearch: true,
    }, {
      title: '门店',
      dataIndex: 'departmentName',
      hideInSearch: true,
    }, {
      title: '门店',
      dataIndex: 'wxDid',
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={departments}
          placeholder="请选择部门"
          treeDefaultExpandAll
        />;
      },
    },
    {
      title: '归属微信群',
      dataIndex: 'wechatGroupName',
      key: 'wechatGroupName',
      hideInSearch: true,
    },
    {
      title: '归属微信群',
      dataIndex: 'wxGid',
      key: 'wxGid',
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={wechatGroups}
          placeholder="请选择微信群"
          treeDefaultExpandAll
        />;
      },
    },
    {
      title: '销售',
      dataIndex: 'salesName',
      hideInSearch: true,
    }, {
      title: '销售',
      dataIndex: 'salesWxUid',
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        // 当表单项被渲染时，使用TreeSelect组件
        return <TreeSelect
          {...rest}
          treeData={sales}
          placeholder="请选择销售"
          treeDefaultExpandAll
        />;
      },
    }, {
      title: '类型',
      dataIndex: 'type',
      hideInSearch: true,
      valueEnum: {
        0: {text: '答题红包',},
        1: {text: '邀请红包',},
      }
    }, {
      title: '创建时间',
      dataIndex: 'createdTime',
      hideInSearch: true,
      render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss')
    }, {
      title: '金额',
      dataIndex: 'amount',
      hideInSearch: true,
    }, {
      title: '获取红包来源',
      dataIndex: 'sourceRemark',
      hideInSearch: true,
    },
    // {
    //   title: '操作',
    //   valueType: 'option',
    //   render: (text, record, _, action) => [
    //     <a key="editable" onClick={() => {
    //       action.startEditable?.(record.id);
    //     }}>
    //       编辑
    //     </a>,
    //   ],
    // }
  ]
  return (
    <PageContainer title={'红包'}>
      <Spin spinning={loading} tip="加载中...">
      <ProTable
        search={true}
        columns={columns}
        actionRef={actionRef}
        request={async (params, sort, filter) => {
          const res = await getAllRedPackets({
            ...params,
            page: currentIndex,
            size
          });
          return {
            data: res.data.records,
            success: true,
            total: res.data.total
          }
        }}
        pagination={{
          pageSize: size,
          onChange: (page) => setCurrentIndex(page),
        }}
      />
      </Spin>
    </PageContainer>
  )
}

export default RedPacket;
